package com.txsj.scan.activity.allocationapply.fragment;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.txsj.scan.AppManager;
import com.txsj.scan.R;
import com.txsj.scan.activity.allocationapply.AllocationApplyDetailsActivity;
import com.txsj.scan.activity.allocationapply.AllocationBatchActivity;
import com.txsj.scan.activity.allocationapply.AllocationEpcActivity;
import com.txsj.scan.adapter.AllocationApplyListAdapter;
import com.txsj.scan.base.BaseFragment;
import com.txsj.scan.bean.AllocationApplyBean;
import com.txsj.scan.bean.EventAllocationBean;
import com.txsj.scan.presenter.AllocationApplyPresenter;
import com.txsj.scan.refresh.XRefreshView;
import com.txsj.scan.view.IAllocationApplyView;
import com.txsj.scan.widget.PinnedHeaderExpandableListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AllocationApplyStateFragment extends BaseFragment<AllocationApplyPresenter> implements IAllocationApplyView
        , PinnedHeaderExpandableListView.OnHeaderUpdateListener {

    AllocationApplyListAdapter adapter;

    XRefreshView xrefresh;
    PinnedHeaderExpandableListView headerExpandableListView;
    boolean isRefresh, isLoadMore;
    Button btn_empty_reload;
    int page = -1;
    List<AllocationApplyBean> list = new ArrayList<>();
    //     状态（-1待审核 -2待出库 -3待入库 -4驳回 -5已完成 -6已作废）
    String startDate = "", endDate = "", wareHouseId = "0", employeeId = "0", stateId = "-1";

    public AllocationApplyStateFragment() {
    }

    public static AllocationApplyStateFragment newInstance() {
        return new AllocationApplyStateFragment();
    }


    @Override
    protected int layoutId() {
        return R.layout.frag_allocation_list;
    }


    @Override
    public void init() {
        EventBus.getDefault().register(this);
        xrefresh = (XRefreshView) rootView.findViewById(R.id.xrefresh);
        headerExpandableListView = (PinnedHeaderExpandableListView) rootView.findViewById(R.id.aah_expandListView);
        adapter = new AllocationApplyListAdapter(getActivity());
        adapter.setAllocateHistoryAdapeterinterface(new AllocationApplyListAdapter.AllocateHistoryAdapeterinterface() {
            @Override
            public void setOnChildClickListener(int groupPosition, int childPosition) {
                Intent intent = new Intent(getActivity(), AllocationApplyDetailsActivity.class);
                intent.putExtra("bill_id", list.get(groupPosition).getList().get(childPosition).getBill_id() + "");
                startActivity(intent);
            }
        });
        headerExpandableListView.setAdapter(adapter);
        // 设置 xrefresh 是否可以下拉刷新
        xrefresh.setPullRefreshEnable(true);
        // 设置 xrefresh 是否可以上拉加载
        xrefresh.setPullLoadEnable(true);
        // 设置 xrefresh 是否可以自动刷新
        xrefresh.enableEmptyView(true);
        xrefresh.startRefresh();
        //当列表数据为空时 显示的View  的 方法
        initEmptyView(xrefresh);
        // xrefresh 的下拉刷新，上拉加载。
        xrefresh.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                //下拉刷新 修改值
                isRefresh = true;
                isLoadMore = false;
                page = 1;
                presenter.getAllocationList(page, startDate, endDate, wareHouseId, employeeId, stateId);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                //下拉加载 修改值
                isRefresh = false;
                isLoadMore = true;
                ++page;
                presenter.getAllocationList(page, startDate, endDate, wareHouseId, employeeId, stateId);
            }
        });
    }

    @Override
    protected AllocationApplyPresenter providePresenter() {
        return new AllocationApplyPresenter(this);
    }

    //    状态（-1待审核 -2待出库 -3待入库 -4驳回 -5已完成 -6已作废）
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(EventAllocationBean message) {

        if (message.isRefresh()) {
            page = 1;
            xrefresh.startRefresh();
            return;
        }


        try {
            JSONObject json = new JSONObject(message.getScreenJson());
            //startDate, endDate, wareHouseId, employeeId, stateName;
            if (json.has("startDate") && !json.isNull("startDate")) {
                startDate = json.getString("startDate");
            }
            if (json.has("endDate") && !json.isNull("endDate")) {
                endDate = json.getString("endDate");
            }
            if (json.has("warehouse") && !json.isNull("warehouse")) {
                wareHouseId = json.getString("warehouse");
            }
            if (json.has("employee") && !json.isNull("employee")) {
                employeeId = json.getString("employee");
            }
            if (json.has("state") && !json.isNull("state")) {
                stateId = json.getString("state");
            }
            page = 1;
            list.clear();
            adapter.notifyDataSetChanged();
            xrefresh.startRefresh();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 列表数据为空时 显示的View  的 方法
     */
    private void initEmptyView(final XRefreshView xRe) {
        View emptyView = View.inflate(getActivity(), R.layout.view_empty, null);
        btn_empty_reload = (Button) emptyView.findViewById(R.id.btn_empty_reload);
        xRe.setEmptyView(emptyView);
        btn_empty_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRe.startRefresh();
            }
        });
    }

    @Override
    public void loadSuccess(List<AllocationApplyBean> dataList) {
        if (null == dataList || dataList.size() == 0) {
            if (isRefresh) {
                // 关闭下拉刷新
                xrefresh.stopRefresh();
            }

            if (isLoadMore) {
                xrefresh.stopLoadMore();
            }
            return;
        }

        //关闭加载框
        hideLoading();
        // 上拉刷新
        if (isRefresh == true) {
            list.clear();
            list.addAll(dataList);
            // 关闭下拉刷新
            xrefresh.stopRefresh();
        } else {
            // 下拉加载
            // 关闭上拉加载
            xrefresh.stopLoadMore();
            if (dataList.size() <= 0) {
                // 返回的数据为空，
                t("已经全部加载完了！！！！！");
                return;
            }

//            //本页面的数据
            if (list.size() > 0) {
                for (int i = list.size() - 1; i > 0; i--) {
                    if (list.get(i).getAdd_time().equals(dataList.get(0).getAdd_time())) {
                        List<AllocationApplyBean.ListBean> list1 = list.get(i).getList();
                        List<AllocationApplyBean.ListBean> list2 = dataList.get(0).getList();
                        list1.addAll(list2);
                        list.get(i).setList(list1);
                        dataList.remove(0);
                        break;
                    }
                }
                list.addAll(dataList);
            } else {
                list.addAll(dataList);
            }
        }
        //adapeter 的 setList方法
        adapter.setList(list);
        //关闭列表数据为空时 显示的View  的 方法
        xrefresh.enableEmptyView(false);
        // PinnedHeaderExpandableListView 头布局  一级列表   的  回调
        headerExpandableListView.setOnHeaderUpdateListener(this);
        //设置默认展开
        for (int i = 0; i < list.size(); i++) {
            headerExpandableListView.expandGroup(i);
        }
    }

    @Override
    public void loadFailed(String errMsg) {
        t(errMsg);
        xrefresh.stopRefresh();
    }

    @Override
    public View getPinnedHeader() {
        View headerView = (ViewGroup) getLayoutInflater().inflate(R.layout.item_allocation_apply_group, null);
        DisplayMetrics outMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        headerView.setLayoutParams(new ViewGroup.LayoutParams(
                (outMetrics.widthPixels), ViewGroup.LayoutParams.WRAP_CONTENT));
        return headerView;
    }

    @Override
    public void updatePinnedHeader(View headerView, int firstVisibleGroupPos) {
        SimpleDateFormat simpleDateFormat0 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (list != null && list.size() > 0) {
                Date date = simpleDateFormat0.parse(list.get(firstVisibleGroupPos).getAdd_time());
                TextView tvhead = (TextView) headerView.findViewById(R.id.tv_group_date);
                TextView tvCount = (TextView) headerView.findViewById(R.id.tv_group_Itemnum);
                tvhead.setText(simpleDateFormat1.format(date));
                tvCount.setText(list.get(firstVisibleGroupPos).getList().size() + "单");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Context context() {
        return activity;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
